package com.shwread.android.ui.page;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.GlideUtil;
import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.activity.AtlasSeeActivity;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw10000227.R;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.android.ui.widget.LoadingView;
import com.shwread.android.ui.widget.refresh.PullToRefreshStaggeredGridView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase.OnRefreshListener;
import com.shwread.android.ui.widget.staggeredgrid.StaggeredGridView;
import com.shwread.android.ui.widget.staggeredgrid.util.DynamicHeightImageView;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.httpsdk.constant.ResultCode;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Random;

import base.tina.core.task.infc.ITaskResult;
import logic.bean.AtlasInfo;
import logic.bean.ImageModuleBean;
import logic.constants.DefaultConsts;
import logic.util.NetworkUtil;
import logic.util.Util;


/**
 * 图集页面
 * 图集瀑布流
 *
 * @author yqq
 * @date 2015年4月10日
 */
public class AtlasPage
        extends
        AbstractUIPage<MainActivity>
        implements
        OnClickListener {

    public static final String ATLAS_ID = "atlasId";
    public static final String ATLAS_NAME = "atlasName";
    private static final SparseArray<Double> sPositionHeightRatios = new SparseArray<Double>();
    private static AtlasPage instance;
    private TextView tvTitle;
    private Button ivPersion;
    private PullToRefreshStaggeredGridView sView;
    private StaggeredGridView sgv;
    private ImageModuleBean resultInfo;
    private SAdapter sAdapter;
    private ArrayList<AtlasInfo> atlasInfos;
    private LoadingView loadingView;
    private ImageView emptyView;
    private View empty;
    private long atlasId;
    private String atlasName;
    private int currentPage = 1;
    private int pageNumber = 20;
    private int totalPage;
    private int totalNumber;
    private Random mRandom;

    public AtlasPage(MainActivity t) {
        super(t);
    }

    // 在MainPage里初始化AtlasPage
    public static AtlasPage getInstance(MainActivity bActivity) {
        if (instance == null) {
            instance = new AtlasPage(bActivity);
        } else {
            instance.setActivity(bActivity);
        }
        return instance;
    }

    @Override
    public <E extends Activity> View createView(E arg0, int arg1) {
        if (null != curMyView) return curMyView;
        curMyView = bActivity.getLayoutInflater().inflate(R.layout.atlas_page_layout, null);

        Bundle bundle = bActivity.getIntent().getExtras();
        if (bundle != null && bundle.containsKey(ATLAS_ID) && bundle.containsKey(ATLAS_NAME)) {
            atlasId = bundle.getLong(ATLAS_ID, 0L);
            atlasName = bundle.getString(ATLAS_NAME);
        }

        atlasInfos = new ArrayList<AtlasInfo>();
        initView();
        addListener();
        //startLoadingImg();
        initLoadingView();

        loadingView.changeLoadingStatus(0);
        loadingView.setVisibility(View.VISIBLE);
        sView.setVisibility(View.GONE);
        getData();

        return curMyView;

    }

    //刷新数据
    private void getData() {
        if (NetworkUtil.isNetAvailable(context)) {
            //new GetAtlasInfoAction(context, atlasId, currentPage, pageNumber, new getAtlasInfoActionListener(0)).start();
            NewActionHelp.qryImageModule(context, currentPage, pageNumber, new ImageModuleHandler(0));//获得数据
        } else {
            new NoNetDialog(context).show();
        }
    }

    public void initView() {
        tvTitle = (TextView) curMyView.findViewById(R.id.common_header_name);
        //tvTitle.setText(Util.isEmpty(atlasName) ? "" : atlasName);
        tvTitle.setText(bActivity.getResources().getString(R.string.maintab_atlas));
        //		tvTitle.setVisibility(View.GONE);
        empty = LayoutInflater.from(context).inflate(R.layout.atlas_body_empty, null);//yqq
        //		flayLoadImg = (FrameLayout) curMyView.findViewById(R.id.atlas_loading_flay);
        //		ivLoadingImg = (ImageView) curMyView.findViewById(R.id.atlas_loading_iv);
        //拉动更新的view
        sView = (PullToRefreshStaggeredGridView) curMyView.findViewById(R.id.atlas_page_layout_gridview);
        sgv = sView.getRefreshableView();
        PullToRefreshUtil.initLabel(context, sView);
    }

    private void addListener() {
        sgv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                intent.setClass(context, AtlasSeeActivity.class);
                intent.putExtra(AtlasSeeActivity.FROM_TYPE, DefaultConsts.TAG_FROM_ATLAS);
                intent.putExtra(ATLAS_ID, atlasInfos.get(position).getAtlasId());
                intent.putExtra("position", position);
                intent.putExtra("atlasInfos", atlasInfos);
                intent.putExtra("currentPage", currentPage + 1);
                intent.putExtra("totalPage", totalPage);
                intent.putExtra("pageNumber", pageNumber);
                intent.putExtra("totalNumber", totalNumber);
                context.startActivity(intent);
            }
        });
        //下拉刷新
        sView.setOnRefreshListener(new OnRefreshListener<StaggeredGridView>() {
            @Override
            public void onRefresh(PullToRefreshBase<StaggeredGridView> refreshView) {
                bActivity.getUIHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        if (sView.isHeaderShown()) {
                            refresh();
                        } else if (sView.isFooterShown()) {
                            loadMore();
                        }
                    }
                });
            }
        });

    }

    /**
     * 下拉刷新
     */
    private void refresh() {
        currentPage = 1;//当前页是首页
        //new GetAtlasInfoAction(context, atlasId, currentPage, pageNumber, new getAtlasInfoActionListener(1)).start();
        NewActionHelp.qryImageModule(context, currentPage, pageNumber, new ImageModuleHandler(1));
    }

    /**
     * 加载更多
     */
    private void loadMore() {
        currentPage++;
        //new GetAtlasInfoAction(context, atlasId, currentPage, pageNumber, new getAtlasInfoActionListener(-1)).start();
        NewActionHelp.qryImageModule(context, currentPage, pageNumber, new ImageModuleHandler(-1));

    }

    @Override
    public int enter(IUIPage<?> arg0) {
        // TODO Auto-generated method stub
        //		NewActionHelp.qryImageModule(context, 1, 5, new ImageModuleHandler(0));
        return 0;
    }

    @Override
    public int leave(IUIPage<?> arg0) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void notifyView(int what, Bundle bundle) {
        switch (what) {
        }

    }

    @Override
    public void setStatus(int arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public View updateView(int arg0, ITaskResult arg1) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
        }

    }

    @SuppressLint("NewApi")
    private void updateUI(int flag) {
        switch (flag) { // 0:首次加载，1：下拉刷新，-1：上拉加载
            case 0:
                sAdapter = new SAdapter();
                sgv.setAdapter(sAdapter);
                //stopLoadingImg();
                break;
            case 1:
                sView.onRefreshComplete();
                // sView.setMode(Mode.BOTH);
                sAdapter.notifyDataSetChanged();
                break;
            case -1:
                sView.onRefreshComplete();
                sAdapter.notifyDataSetChanged();
                if (currentPage >= totalPage) {
                    PullToRefreshUtil.setLoadLabel(sView, "没有更多数据了");
                    // sView.setMode(Mode.PULL_FROM_START);
                }
                break;
        }
    }

    //	private void startLoadingImg() {
    //		flayLoadImg.setVisibility(View.VISIBLE);
    //		ivLoadingImg.setBackgroundResource(R.anim.home_progress);
    //		//		ivLoadingImg.setBackgroundResource(R.anim.column_switch_anim);
    //		switchDrawable = (AnimationDrawable) ivLoadingImg.getBackground();
    //		switchDrawable.start();
    //	}
    //
    //	private void stopLoadingImg() {
    //		flayLoadImg.setVisibility(View.GONE);
    //		if (switchDrawable != null && switchDrawable.isRunning())
    //		{
    //			switchDrawable.stop();
    //		}
    //	}
    private void initLoadingView() {
        loadingView = (LoadingView) curMyView.findViewById(R.id.atlas_page_loading_view);
        //loadingView.setDefaultConfig();
        loadingView.setLoadingAnim(R.drawable.home_progress);//替换默认动画
        loadingView.setEmptyView(empty);//替换默认的空白页
        loadingView.setEmptyClickListener(new ViewClick());
        loadingView.setFailClickListener(new ViewClick());

    }

    private double getPositionRatio(final int position) {
        double ratio = sPositionHeightRatios.get(position, 0.0);
        // if not yet done generate and stash the columns height
        // in our real world scenario this will be determined by
        // some match based on the known height and width of the image
        // and maybe a helpful way to get the column height!
        if (ratio == 0) {
            ratio = getRandomHeightRatio();
            sPositionHeightRatios.append(position, ratio);
        }
        return ratio;
    }

    private double getRandomHeightRatio() {
        return (mRandom.nextDouble() / 2.0) + 1.0; // height will be 1.0 - 1.5
        // the width
    }

    private class ImageModuleHandler
            extends
            ObjectHttpResponseHandler<ImageModuleBean> {
        private int flag;

        /**
         * @param flag 0:首次加载，1：下拉刷新，-1：上拉加载
         */
        public ImageModuleHandler(int flag) {
            super();
            this.flag = flag;
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, ImageModuleBean object, String responseString) {
            System.out.println(responseString);
            resultInfo = object;
            totalPage = resultInfo.getPage().getTotalPage();
            totalNumber = resultInfo.getPage().getTotalNum();
            if (atlasInfos != null && flag != -1) atlasInfos.clear();
            if (resultInfo != null && resultInfo.getImageList() != null && resultInfo.getImageList().size() > 0) {
                atlasInfos.addAll(resultInfo.getImageList());
                updateUI(flag);
                loadingView.setVisibility(View.GONE);
                sView.setVisibility(View.VISIBLE);
            } else {
                //TODO
                if (flag == -1) updateUI(flag);//上拉加载
                loadingView.changeLoadingStatus(1);//首次加载显示空白页
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            //stopLoadingImg();
            loadingView.changeLoadingStatus(-1);
            if (statusCode == ResultCode.E_3003) {
                Util.showToast(context, ResultCode.getResultText(statusCode));
            }
        }

        @Override
        public Type getType() {
            return new TypeToken<ImageModuleBean>() {
            }.getType();
        }
    }

    private class ViewClick
            implements
            OnClickListener {
        @Override
        public void onClick(View v) {
            loadingView.changeLoadingStatus(0);
            loadingView.setVisibility(View.VISIBLE);
            sView.setVisibility(View.GONE);
            getData();
        }
    }

    class SAdapter
            extends
            BaseAdapter {
        AtlasHolder atlasHolder;

        public SAdapter() {
            mRandom = new Random();
        }

        @Override
        public int getCount() {
            return (atlasInfos == null || atlasInfos.isEmpty()) ? 0 : atlasInfos.size();

        }

        @Override
        public Object getItem(int position) {
            return (atlasInfos == null || atlasInfos.isEmpty()) ? null : atlasInfos.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            atlasHolder = new AtlasHolder();
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.atlas_item, null);
                atlasHolder.dImage = (DynamicHeightImageView) convertView.findViewById(R.id.atlas_item_atlas_image_iv);
                atlasHolder.tvTitle = (TextView) convertView.findViewById(R.id.atlas_item_atlas_title_tv);
                convertView.setTag(atlasHolder);
            } else {
                atlasHolder = (AtlasHolder) convertView.getTag();
            }
            AtlasInfo info = (AtlasInfo) getItem(position);
            if (null != info) {
                if (info.getImageThumbnailHeight() > DynamicHeightImageView.MIN_WH && info.getImageThumbnailWidth() > DynamicHeightImageView.MIN_WH) {
                    atlasHolder.dImage.setWH(info.getImageThumbnailWidth(), info.getImageThumbnailHeight());
                } else {// 缩略图宽高太小时，用默认的算法
                    double positionHeight = getPositionRatio(position);
                    atlasHolder.dImage.setHeightRatio(positionHeight);
                }
                // 网络图片
                if (Util.isNotEmpty(info.getImageThumbnailUrl())) {
                    GlideUtil.load(context,info.getImageThumbnailUrl(), R.drawable.atlas_default_img, atlasHolder.dImage);
                } else {
                    atlasHolder.dImage.setImageResource(R.drawable.atlas_default_img);
                }
                atlasHolder.tvTitle.setText(Util.isNotEmpty(info.getImageName()) ? info.getImageName() : "");
            }
            return convertView;
        }

    }

    class AtlasHolder {
        private TextView tvTitle;
        private DynamicHeightImageView dImage;
    }
}
